home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / Miro_Downloader.exe / subprocess.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-11-12  |  29.5 KB  |  1,109 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''subprocess - Subprocesses with accessible I/O streams
  5.  
  6. This module allows you to spawn processes, connect to their
  7. input/output/error pipes, and obtain their return codes.  This module
  8. intends to replace several other, older modules and functions, like:
  9.  
  10. os.system
  11. os.spawn*
  12. os.popen*
  13. popen2.*
  14. commands.*
  15.  
  16. Information about how the subprocess module can be used to replace these
  17. modules and functions can be found below.
  18.  
  19.  
  20.  
  21. Using the subprocess module
  22. ===========================
  23. This module defines one class called Popen:
  24.  
  25. class Popen(args, bufsize=0, executable=None,
  26.             stdin=None, stdout=None, stderr=None,
  27.             preexec_fn=None, close_fds=False, shell=False,
  28.             cwd=None, env=None, universal_newlines=False,
  29.             startupinfo=None, creationflags=0):
  30.  
  31.  
  32. Arguments are:
  33.  
  34. args should be a string, or a sequence of program arguments.  The
  35. program to execute is normally the first item in the args sequence or
  36. string, but can be explicitly set by using the executable argument.
  37.  
  38. On UNIX, with shell=False (default): In this case, the Popen class
  39. uses os.execvp() to execute the child program.  args should normally
  40. be a sequence.  A string will be treated as a sequence with the string
  41. as the only item (the program to execute).
  42.  
  43. On UNIX, with shell=True: If args is a string, it specifies the
  44. command string to execute through the shell.  If args is a sequence,
  45. the first item specifies the command string, and any additional items
  46. will be treated as additional shell arguments.
  47.  
  48. On Windows: the Popen class uses CreateProcess() to execute the child
  49. program, which operates on strings.  If args is a sequence, it will be
  50. converted to a string using the list2cmdline method.  Please note that
  51. not all MS Windows applications interpret the command line the same
  52. way: The list2cmdline is designed for applications using the same
  53. rules as the MS C runtime.
  54.  
  55. bufsize, if given, has the same meaning as the corresponding argument
  56. to the built-in open() function: 0 means unbuffered, 1 means line
  57. buffered, any other positive value means use a buffer of
  58. (approximately) that size.  A negative bufsize means to use the system
  59. default, which usually means fully buffered.  The default value for
  60. bufsize is 0 (unbuffered).
  61.  
  62. stdin, stdout and stderr specify the executed programs\' standard
  63. input, standard output and standard error file handles, respectively.
  64. Valid values are PIPE, an existing file descriptor (a positive
  65. integer), an existing file object, and None.  PIPE indicates that a
  66. new pipe to the child should be created.  With None, no redirection
  67. will occur; the child\'s file handles will be inherited from the
  68. parent.  Additionally, stderr can be STDOUT, which indicates that the
  69. stderr data from the applications should be captured into the same
  70. file handle as for stdout.
  71.  
  72. If preexec_fn is set to a callable object, this object will be called
  73. in the child process just before the child is executed.
  74.  
  75. If close_fds is true, all file descriptors except 0, 1 and 2 will be
  76. closed before the child process is executed.
  77.  
  78. if shell is true, the specified command will be executed through the
  79. shell.
  80.  
  81. If cwd is not None, the current directory will be changed to cwd
  82. before the child is executed.
  83.  
  84. If env is not None, it defines the environment variables for the new
  85. process.
  86.  
  87. If universal_newlines is true, the file objects stdout and stderr are
  88. opened as a text files, but lines may be terminated by any of \'\\n\',
  89. the Unix end-of-line convention, \'\\r\', the Macintosh convention or
  90. \'\\r\\n\', the Windows convention.  All of these external representations
  91. are seen as \'\\n\' by the Python program.  Note: This feature is only
  92. available if Python is built with universal newline support (the
  93. default).  Also, the newlines attribute of the file objects stdout,
  94. stdin and stderr are not updated by the communicate() method.
  95.  
  96. The startupinfo and creationflags, if given, will be passed to the
  97. underlying CreateProcess() function.  They can specify things such as
  98. appearance of the main window and priority for the new process.
  99. (Windows only)
  100.  
  101.  
  102. This module also defines two shortcut functions:
  103.  
  104. call(*popenargs, **kwargs):
  105.     Run command with arguments.  Wait for command to complete, then
  106.     return the returncode attribute.
  107.  
  108.     The arguments are the same as for the Popen constructor.  Example:
  109.  
  110.     retcode = call(["ls", "-l"])
  111.  
  112. check_call(*popenargs, **kwargs):
  113.     Run command with arguments.  Wait for command to complete.  If the
  114.     exit code was zero then return, otherwise raise
  115.     CalledProcessError.  The CalledProcessError object will have the
  116.     return code in the returncode attribute.
  117.  
  118.     The arguments are the same as for the Popen constructor.  Example:
  119.  
  120.     check_call(["ls", "-l"])
  121.  
  122. Exceptions
  123. ----------
  124. Exceptions raised in the child process, before the new program has
  125. started to execute, will be re-raised in the parent.  Additionally,
  126. the exception object will have one extra attribute called
  127. \'child_traceback\', which is a string containing traceback information
  128. from the childs point of view.
  129.  
  130. The most common exception raised is OSError.  This occurs, for
  131. example, when trying to execute a non-existent file.  Applications
  132. should prepare for OSErrors.
  133.  
  134. A ValueError will be raised if Popen is called with invalid arguments.
  135.  
  136. check_call() will raise CalledProcessError, if the called process
  137. returns a non-zero return code.
  138.  
  139.  
  140. Security
  141. --------
  142. Unlike some other popen functions, this implementation will never call
  143. /bin/sh implicitly.  This means that all characters, including shell
  144. metacharacters, can safely be passed to child processes.
  145.  
  146.  
  147. Popen objects
  148. =============
  149. Instances of the Popen class have the following methods:
  150.  
  151. poll()
  152.     Check if child process has terminated.  Returns returncode
  153.     attribute.
  154.  
  155. wait()
  156.     Wait for child process to terminate.  Returns returncode attribute.
  157.  
  158. communicate(input=None)
  159.     Interact with process: Send data to stdin.  Read data from stdout
  160.     and stderr, until end-of-file is reached.  Wait for process to
  161.     terminate.  The optional stdin argument should be a string to be
  162.     sent to the child process, or None, if no data should be sent to
  163.     the child.
  164.  
  165.     communicate() returns a tuple (stdout, stderr).
  166.  
  167.     Note: The data read is buffered in memory, so do not use this
  168.     method if the data size is large or unlimited.
  169.  
  170. The following attributes are also available:
  171.  
  172. stdin
  173.     If the stdin argument is PIPE, this attribute is a file object
  174.     that provides input to the child process.  Otherwise, it is None.
  175.  
  176. stdout
  177.     If the stdout argument is PIPE, this attribute is a file object
  178.     that provides output from the child process.  Otherwise, it is
  179.     None.
  180.  
  181. stderr
  182.     If the stderr argument is PIPE, this attribute is file object that
  183.     provides error output from the child process.  Otherwise, it is
  184.     None.
  185.  
  186. pid
  187.     The process ID of the child process.
  188.  
  189. returncode
  190.     The child return code.  A None value indicates that the process
  191.     hasn\'t terminated yet.  A negative value -N indicates that the
  192.     child was terminated by signal N (UNIX only).
  193.  
  194.  
  195. Replacing older functions with the subprocess module
  196. ====================================================
  197. In this section, "a ==> b" means that b can be used as a replacement
  198. for a.
  199.  
  200. Note: All functions in this section fail (more or less) silently if
  201. the executed program cannot be found; this module raises an OSError
  202. exception.
  203.  
  204. In the following examples, we assume that the subprocess module is
  205. imported with "from subprocess import *".
  206.  
  207.  
  208. Replacing /bin/sh shell backquote
  209. ---------------------------------
  210. output=`mycmd myarg`
  211. ==>
  212. output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
  213.  
  214.  
  215. Replacing shell pipe line
  216. -------------------------
  217. output=`dmesg | grep hda`
  218. ==>
  219. p1 = Popen(["dmesg"], stdout=PIPE)
  220. p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  221. output = p2.communicate()[0]
  222.  
  223.  
  224. Replacing os.system()
  225. ---------------------
  226. sts = os.system("mycmd" + " myarg")
  227. ==>
  228. p = Popen("mycmd" + " myarg", shell=True)
  229. pid, sts = os.waitpid(p.pid, 0)
  230.  
  231. Note:
  232.  
  233. * Calling the program through the shell is usually not required.
  234.  
  235. * It\'s easier to look at the returncode attribute than the
  236.   exitstatus.
  237.  
  238. A more real-world example would look like this:
  239.  
  240. try:
  241.     retcode = call("mycmd" + " myarg", shell=True)
  242.     if retcode < 0:
  243.         print >>sys.stderr, "Child was terminated by signal", -retcode
  244.     else:
  245.         print >>sys.stderr, "Child returned", retcode
  246. except OSError, e:
  247.     print >>sys.stderr, "Execution failed:", e
  248.  
  249.  
  250. Replacing os.spawn*
  251. -------------------
  252. P_NOWAIT example:
  253.  
  254. pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
  255. ==>
  256. pid = Popen(["/bin/mycmd", "myarg"]).pid
  257.  
  258.  
  259. P_WAIT example:
  260.  
  261. retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
  262. ==>
  263. retcode = call(["/bin/mycmd", "myarg"])
  264.  
  265.  
  266. Vector example:
  267.  
  268. os.spawnvp(os.P_NOWAIT, path, args)
  269. ==>
  270. Popen([path] + args[1:])
  271.  
  272.  
  273. Environment example:
  274.  
  275. os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
  276. ==>
  277. Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
  278.  
  279.  
  280. Replacing os.popen*
  281. -------------------
  282. pipe = os.popen(cmd, mode=\'r\', bufsize)
  283. ==>
  284. pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
  285.  
  286. pipe = os.popen(cmd, mode=\'w\', bufsize)
  287. ==>
  288. pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
  289.  
  290.  
  291. (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
  292. ==>
  293. p = Popen(cmd, shell=True, bufsize=bufsize,
  294.           stdin=PIPE, stdout=PIPE, close_fds=True)
  295. (child_stdin, child_stdout) = (p.stdin, p.stdout)
  296.  
  297.  
  298. (child_stdin,
  299.  child_stdout,
  300.  child_stderr) = os.popen3(cmd, mode, bufsize)
  301. ==>
  302. p = Popen(cmd, shell=True, bufsize=bufsize,
  303.           stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
  304. (child_stdin,
  305.  child_stdout,
  306.  child_stderr) = (p.stdin, p.stdout, p.stderr)
  307.  
  308.  
  309. (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
  310. ==>
  311. p = Popen(cmd, shell=True, bufsize=bufsize,
  312.           stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  313. (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
  314.  
  315.  
  316. Replacing popen2.*
  317. ------------------
  318. Note: If the cmd argument to popen2 functions is a string, the command
  319. is executed through /bin/sh.  If it is a list, the command is directly
  320. executed.
  321.  
  322. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
  323. ==>
  324. p = Popen(["somestring"], shell=True, bufsize=bufsize
  325.           stdin=PIPE, stdout=PIPE, close_fds=True)
  326. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  327.  
  328.  
  329. (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
  330. ==>
  331. p = Popen(["mycmd", "myarg"], bufsize=bufsize,
  332.           stdin=PIPE, stdout=PIPE, close_fds=True)
  333. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  334.  
  335. The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
  336. except that:
  337.  
  338. * subprocess.Popen raises an exception if the execution fails
  339. * the capturestderr argument is replaced with the stderr argument.
  340. * stdin=PIPE and stdout=PIPE must be specified.
  341. * popen2 closes all filedescriptors by default, but you have to specify
  342.   close_fds=True with subprocess.Popen.
  343.  
  344.  
  345. '''
  346. import sys
  347. mswindows = sys.platform == 'win32'
  348. import os
  349. import types
  350. import traceback
  351.  
  352. class CalledProcessError(Exception):
  353.     '''This exception is raised when a process run by check_call() returns
  354.     a non-zero exit status.  The exit status will be stored in the
  355.     returncode attribute.'''
  356.     
  357.     def __init__(self, returncode, cmd):
  358.         self.returncode = returncode
  359.         self.cmd = cmd
  360.  
  361.     
  362.     def __str__(self):
  363.         return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
  364.  
  365.  
  366. if mswindows:
  367.     import threading
  368.     import msvcrt
  369.     from _subprocess import *
  370.     
  371.     class STARTUPINFO:
  372.         dwFlags = 0
  373.         hStdInput = None
  374.         hStdOutput = None
  375.         hStdError = None
  376.         wShowWindow = 0
  377.  
  378.     
  379.     class pywintypes:
  380.         error = IOError
  381.  
  382. else:
  383.     import select
  384.     import errno
  385.     import fcntl
  386.     import pickle
  387. __all__ = [
  388.     'Popen',
  389.     'PIPE',
  390.     'STDOUT',
  391.     'call',
  392.     'check_call',
  393.     'CalledProcessError']
  394.  
  395. try:
  396.     MAXFD = os.sysconf('SC_OPEN_MAX')
  397. except:
  398.     MAXFD = 256
  399.  
  400.  
  401. try:
  402.     False
  403. except NameError:
  404.     False = 0
  405.     True = 1
  406.  
  407. _active = []
  408.  
  409. def _cleanup():
  410.     for inst in _active[:]:
  411.         if inst.poll(_deadstate = sys.maxint) >= 0:
  412.             
  413.             try:
  414.                 _active.remove(inst)
  415.             except ValueError:
  416.                 pass
  417.             except:
  418.                 None<EXCEPTION MATCH>ValueError
  419.             
  420.  
  421.         None<EXCEPTION MATCH>ValueError
  422.     
  423.  
  424. PIPE = -1
  425. STDOUT = -2
  426.  
  427. def call(*popenargs, **kwargs):
  428.     '''Run command with arguments.  Wait for command to complete, then
  429.     return the returncode attribute.
  430.  
  431.     The arguments are the same as for the Popen constructor.  Example:
  432.  
  433.     retcode = call(["ls", "-l"])
  434.     '''
  435.     return Popen(*popenargs, **kwargs).wait()
  436.  
  437.  
  438. def check_call(*popenargs, **kwargs):
  439.     '''Run command with arguments.  Wait for command to complete.  If
  440.     the exit code was zero then return, otherwise raise
  441.     CalledProcessError.  The CalledProcessError object will have the
  442.     return code in the returncode attribute.
  443.  
  444.     The arguments are the same as for the Popen constructor.  Example:
  445.  
  446.     check_call(["ls", "-l"])
  447.     '''
  448.     retcode = call(*popenargs, **kwargs)
  449.     cmd = kwargs.get('args')
  450.     if cmd is None:
  451.         cmd = popenargs[0]
  452.     
  453.     if retcode:
  454.         raise CalledProcessError(retcode, cmd)
  455.     
  456.     return retcode
  457.  
  458.  
  459. def list2cmdline(seq):
  460.     '''
  461.     Translate a sequence of arguments into a command line
  462.     string, using the same rules as the MS C runtime:
  463.  
  464.     1) Arguments are delimited by white space, which is either a
  465.        space or a tab.
  466.  
  467.     2) A string surrounded by double quotation marks is
  468.        interpreted as a single argument, regardless of white space
  469.        contained within.  A quoted string can be embedded in an
  470.        argument.
  471.  
  472.     3) A double quotation mark preceded by a backslash is
  473.        interpreted as a literal double quotation mark.
  474.  
  475.     4) Backslashes are interpreted literally, unless they
  476.        immediately precede a double quotation mark.
  477.  
  478.     5) If backslashes immediately precede a double quotation mark,
  479.        every pair of backslashes is interpreted as a literal
  480.        backslash.  If the number of backslashes is odd, the last
  481.        backslash escapes the next double quotation mark as
  482.        described in rule 3.
  483.     '''
  484.     result = []
  485.     needquote = False
  486.     for arg in seq:
  487.         bs_buf = []
  488.         if result:
  489.             result.append(' ')
  490.         
  491.         if not ' ' in arg:
  492.             pass
  493.         needquote = '\t' in arg
  494.         if needquote:
  495.             result.append('"')
  496.         
  497.         for c in arg:
  498.             if c == '\\':
  499.                 bs_buf.append(c)
  500.                 continue
  501.             if c == '"':
  502.                 result.append('\\' * len(bs_buf) * 2)
  503.                 bs_buf = []
  504.                 result.append('\\"')
  505.                 continue
  506.             if bs_buf:
  507.                 result.extend(bs_buf)
  508.                 bs_buf = []
  509.             
  510.             result.append(c)
  511.         
  512.         if bs_buf:
  513.             result.extend(bs_buf)
  514.         
  515.         if needquote:
  516.             result.extend(bs_buf)
  517.             result.append('"')
  518.             continue
  519.     
  520.     return ''.join(result)
  521.  
  522.  
  523. class Popen(object):
  524.     
  525.     def __init__(self, args, bufsize = 0, executable = None, stdin = None, stdout = None, stderr = None, preexec_fn = None, close_fds = False, shell = False, cwd = None, env = None, universal_newlines = False, startupinfo = None, creationflags = 0):
  526.         '''Create new Popen instance.'''
  527.         _cleanup()
  528.         self._child_created = False
  529.         if not isinstance(bufsize, (int, long)):
  530.             raise TypeError('bufsize must be an integer')
  531.         
  532.         if mswindows:
  533.             if preexec_fn is not None:
  534.                 raise ValueError('preexec_fn is not supported on Windows platforms')
  535.             
  536.             if close_fds:
  537.                 raise ValueError('close_fds is not supported on Windows platforms')
  538.             
  539.         elif startupinfo is not None:
  540.             raise ValueError('startupinfo is only supported on Windows platforms')
  541.         
  542.         if creationflags != 0:
  543.             raise ValueError('creationflags is only supported on Windows platforms')
  544.         
  545.         self.stdin = None
  546.         self.stdout = None
  547.         self.stderr = None
  548.         self.pid = None
  549.         self.returncode = None
  550.         self.universal_newlines = universal_newlines
  551.         (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  552.         self._execute_child(args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  553.         if p2cwrite:
  554.             self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
  555.         
  556.         if c2pread:
  557.             if universal_newlines:
  558.                 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
  559.             else:
  560.                 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
  561.         
  562.         if errread:
  563.             if universal_newlines:
  564.                 self.stderr = os.fdopen(errread, 'rU', bufsize)
  565.             else:
  566.                 self.stderr = os.fdopen(errread, 'rb', bufsize)
  567.         
  568.  
  569.     
  570.     def _translate_newlines(self, data):
  571.         data = data.replace('\r\n', '\n')
  572.         data = data.replace('\r', '\n')
  573.         return data
  574.  
  575.     
  576.     def __del__(self):
  577.         if not self._child_created:
  578.             return None
  579.         
  580.         self.poll(_deadstate = sys.maxint)
  581.         if self.returncode is None and _active is not None:
  582.             _active.append(self)
  583.         
  584.  
  585.     
  586.     def communicate(self, input = None):
  587.         '''Interact with process: Send data to stdin.  Read data from
  588.         stdout and stderr, until end-of-file is reached.  Wait for
  589.         process to terminate.  The optional input argument should be a
  590.         string to be sent to the child process, or None, if no data
  591.         should be sent to the child.
  592.  
  593.         communicate() returns a tuple (stdout, stderr).'''
  594.         if [
  595.             self.stdin,
  596.             self.stdout,
  597.             self.stderr].count(None) >= 2:
  598.             stdout = None
  599.             stderr = None
  600.             if self.stdin:
  601.                 if input:
  602.                     self.stdin.write(input)
  603.                 
  604.                 self.stdin.close()
  605.             elif self.stdout:
  606.                 stdout = self.stdout.read()
  607.             elif self.stderr:
  608.                 stderr = self.stderr.read()
  609.             
  610.             self.wait()
  611.             return (stdout, stderr)
  612.         
  613.         return self._communicate(input)
  614.  
  615.     if mswindows:
  616.         
  617.         def _get_handles(self, stdin, stdout, stderr):
  618.             '''Construct and return tupel with IO objects:
  619.             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  620.             '''
  621.             if stdin is None and stdout is None and stderr is None:
  622.                 return (None, None, None, None, None, None)
  623.             
  624.             p2cread = None
  625.             p2cwrite = None
  626.             c2pread = None
  627.             c2pwrite = None
  628.             errread = None
  629.             errwrite = None
  630.             if stdin is None:
  631.                 p2cread = GetStdHandle(STD_INPUT_HANDLE)
  632.             elif stdin == PIPE:
  633.                 (p2cread, p2cwrite) = CreatePipe(None, 0)
  634.                 p2cwrite = p2cwrite.Detach()
  635.                 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
  636.             elif isinstance(stdin, int):
  637.                 p2cread = msvcrt.get_osfhandle(stdin)
  638.             else:
  639.                 p2cread = msvcrt.get_osfhandle(stdin.fileno())
  640.             p2cread = self._make_inheritable(p2cread)
  641.             if stdout is None:
  642.                 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
  643.             elif stdout == PIPE:
  644.                 (c2pread, c2pwrite) = CreatePipe(None, 0)
  645.                 c2pread = c2pread.Detach()
  646.                 c2pread = msvcrt.open_osfhandle(c2pread, 0)
  647.             elif isinstance(stdout, int):
  648.                 c2pwrite = msvcrt.get_osfhandle(stdout)
  649.             else:
  650.                 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  651.             c2pwrite = self._make_inheritable(c2pwrite)
  652.             if stderr is None:
  653.                 errwrite = GetStdHandle(STD_ERROR_HANDLE)
  654.             elif stderr == PIPE:
  655.                 (errread, errwrite) = CreatePipe(None, 0)
  656.                 errread = errread.Detach()
  657.                 errread = msvcrt.open_osfhandle(errread, 0)
  658.             elif stderr == STDOUT:
  659.                 errwrite = c2pwrite
  660.             elif isinstance(stderr, int):
  661.                 errwrite = msvcrt.get_osfhandle(stderr)
  662.             else:
  663.                 errwrite = msvcrt.get_osfhandle(stderr.fileno())
  664.             errwrite = self._make_inheritable(errwrite)
  665.             return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  666.  
  667.         
  668.         def _make_inheritable(self, handle):
  669.             '''Return a duplicate of handle, which is inheritable'''
  670.             return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS)
  671.  
  672.         
  673.         def _find_w9xpopen(self):
  674.             '''Find and return absolut path to w9xpopen.exe'''
  675.             w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), 'w9xpopen.exe')
  676.             if not os.path.exists(w9xpopen):
  677.                 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), 'w9xpopen.exe')
  678.                 if not os.path.exists(w9xpopen):
  679.                     raise RuntimeError('Cannot locate w9xpopen.exe, which is needed for Popen to work with your shell or platform.')
  680.                 
  681.             
  682.             return w9xpopen
  683.  
  684.         
  685.         def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite):
  686.             '''Execute program (MS Windows version)'''
  687.             if not isinstance(args, types.StringTypes):
  688.                 args = list2cmdline(args)
  689.             
  690.             if startupinfo is None:
  691.                 startupinfo = STARTUPINFO()
  692.             
  693.             if None not in (p2cread, c2pwrite, errwrite):
  694.                 startupinfo.dwFlags |= STARTF_USESTDHANDLES
  695.                 startupinfo.hStdInput = p2cread
  696.                 startupinfo.hStdOutput = c2pwrite
  697.                 startupinfo.hStdError = errwrite
  698.             
  699.             if shell:
  700.                 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
  701.                 startupinfo.wShowWindow = SW_HIDE
  702.                 comspec = os.environ.get('COMSPEC', 'cmd.exe')
  703.                 args = comspec + ' /c ' + args
  704.                 if GetVersion() >= 0x80000000L or os.path.basename(comspec).lower() == 'command.com':
  705.                     w9xpopen = self._find_w9xpopen()
  706.                     args = '"%s" %s' % (w9xpopen, args)
  707.                     creationflags |= CREATE_NEW_CONSOLE
  708.                 
  709.             
  710.             
  711.             try:
  712.                 (hp, ht, pid, tid) = CreateProcess(executable, args, None, None, 1, creationflags, env, cwd, startupinfo)
  713.             except pywintypes.error:
  714.                 e = None
  715.                 raise WindowsError(*e.args)
  716.  
  717.             self._child_created = True
  718.             self._handle = hp
  719.             self.pid = pid
  720.             ht.Close()
  721.             if p2cread is not None:
  722.                 p2cread.Close()
  723.             
  724.             if c2pwrite is not None:
  725.                 c2pwrite.Close()
  726.             
  727.             if errwrite is not None:
  728.                 errwrite.Close()
  729.             
  730.  
  731.         
  732.         def poll(self, _deadstate = None):
  733.             '''Check if child process has terminated.  Returns returncode
  734.             attribute.'''
  735.             if self.returncode is None:
  736.                 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
  737.                     self.returncode = GetExitCodeProcess(self._handle)
  738.                 
  739.             
  740.             return self.returncode
  741.  
  742.         
  743.         def wait(self):
  744.             '''Wait for child process to terminate.  Returns returncode
  745.             attribute.'''
  746.             if self.returncode is None:
  747.                 obj = WaitForSingleObject(self._handle, INFINITE)
  748.                 self.returncode = GetExitCodeProcess(self._handle)
  749.             
  750.             return self.returncode
  751.  
  752.         
  753.         def _readerthread(self, fh, buffer):
  754.             buffer.append(fh.read())
  755.  
  756.         
  757.         def _communicate(self, input):
  758.             stdout = None
  759.             stderr = None
  760.             if self.stdout:
  761.                 stdout = []
  762.                 stdout_thread = threading.Thread(target = self._readerthread, args = (self.stdout, stdout))
  763.                 stdout_thread.setDaemon(True)
  764.                 stdout_thread.start()
  765.             
  766.             if self.stderr:
  767.                 stderr = []
  768.                 stderr_thread = threading.Thread(target = self._readerthread, args = (self.stderr, stderr))
  769.                 stderr_thread.setDaemon(True)
  770.                 stderr_thread.start()
  771.             
  772.             if self.stdin:
  773.                 if input is not None:
  774.                     self.stdin.write(input)
  775.                 
  776.                 self.stdin.close()
  777.             
  778.             if self.stdout:
  779.                 stdout_thread.join()
  780.             
  781.             if self.stderr:
  782.                 stderr_thread.join()
  783.             
  784.             if stdout is not None:
  785.                 stdout = stdout[0]
  786.             
  787.             if stderr is not None:
  788.                 stderr = stderr[0]
  789.             
  790.             if self.universal_newlines and hasattr(file, 'newlines'):
  791.                 if stdout:
  792.                     stdout = self._translate_newlines(stdout)
  793.                 
  794.                 if stderr:
  795.                     stderr = self._translate_newlines(stderr)
  796.                 
  797.             
  798.             self.wait()
  799.             return (stdout, stderr)
  800.  
  801.     else:
  802.         
  803.         def _get_handles(self, stdin, stdout, stderr):
  804.             '''Construct and return tupel with IO objects:
  805.             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  806.             '''
  807.             p2cread = None
  808.             p2cwrite = None
  809.             c2pread = None
  810.             c2pwrite = None
  811.             errread = None
  812.             errwrite = None
  813.             if stdin is None:
  814.                 pass
  815.             elif stdin == PIPE:
  816.                 (p2cread, p2cwrite) = os.pipe()
  817.             elif isinstance(stdin, int):
  818.                 p2cread = stdin
  819.             else:
  820.                 p2cread = stdin.fileno()
  821.             if stdout is None:
  822.                 pass
  823.             elif stdout == PIPE:
  824.                 (c2pread, c2pwrite) = os.pipe()
  825.             elif isinstance(stdout, int):
  826.                 c2pwrite = stdout
  827.             else:
  828.                 c2pwrite = stdout.fileno()
  829.             if stderr is None:
  830.                 pass
  831.             elif stderr == PIPE:
  832.                 (errread, errwrite) = os.pipe()
  833.             elif stderr == STDOUT:
  834.                 errwrite = c2pwrite
  835.             elif isinstance(stderr, int):
  836.                 errwrite = stderr
  837.             else:
  838.                 errwrite = stderr.fileno()
  839.             return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  840.  
  841.         
  842.         def _set_cloexec_flag(self, fd):
  843.             
  844.             try:
  845.                 cloexec_flag = fcntl.FD_CLOEXEC
  846.             except AttributeError:
  847.                 cloexec_flag = 1
  848.  
  849.             old = fcntl.fcntl(fd, fcntl.F_GETFD)
  850.             fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
  851.  
  852.         
  853.         def _close_fds(self, but):
  854.             for i in xrange(3, MAXFD):
  855.                 if i == but:
  856.                     continue
  857.                 
  858.                 
  859.                 try:
  860.                     os.close(i)
  861.                 continue
  862.                 continue
  863.  
  864.             
  865.  
  866.         
  867.         def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite):
  868.             '''Execute program (POSIX version)'''
  869.             if isinstance(args, types.StringTypes):
  870.                 args = [
  871.                     args]
  872.             
  873.             if shell:
  874.                 args = [
  875.                     '/bin/sh',
  876.                     '-c'] + args
  877.             
  878.             if executable is None:
  879.                 executable = args[0]
  880.             
  881.             (errpipe_read, errpipe_write) = os.pipe()
  882.             self._set_cloexec_flag(errpipe_write)
  883.             self.pid = os.fork()
  884.             self._child_created = True
  885.             if self.pid == 0:
  886.                 
  887.                 try:
  888.                     if p2cwrite:
  889.                         os.close(p2cwrite)
  890.                     
  891.                     if c2pread:
  892.                         os.close(c2pread)
  893.                     
  894.                     if errread:
  895.                         os.close(errread)
  896.                     
  897.                     os.close(errpipe_read)
  898.                     if p2cread:
  899.                         os.dup2(p2cread, 0)
  900.                     
  901.                     if c2pwrite:
  902.                         os.dup2(c2pwrite, 1)
  903.                     
  904.                     if errwrite:
  905.                         os.dup2(errwrite, 2)
  906.                     
  907.                     for fd in set((p2cread, c2pwrite, errwrite)) - set((0, 1, 2)):
  908.                         if fd:
  909.                             os.close(fd)
  910.                             continue
  911.                     
  912.                     if close_fds:
  913.                         self._close_fds(but = errpipe_write)
  914.                     
  915.                     if cwd is not None:
  916.                         os.chdir(cwd)
  917.                     
  918.                     if preexec_fn:
  919.                         apply(preexec_fn)
  920.                     
  921.                     if env is None:
  922.                         os.execvp(executable, args)
  923.                     else:
  924.                         os.execvpe(executable, args, env)
  925.                 except:
  926.                     (exc_type, exc_value, tb) = sys.exc_info()
  927.                     exc_lines = traceback.format_exception(exc_type, exc_value, tb)
  928.                     exc_value.child_traceback = ''.join(exc_lines)
  929.                     os.write(errpipe_write, pickle.dumps(exc_value))
  930.  
  931.                 os._exit(255)
  932.             
  933.             os.close(errpipe_write)
  934.             if p2cread and p2cwrite:
  935.                 os.close(p2cread)
  936.             
  937.             if c2pwrite and c2pread:
  938.                 os.close(c2pwrite)
  939.             
  940.             if errwrite and errread:
  941.                 os.close(errwrite)
  942.             
  943.             data = os.read(errpipe_read, 1048576)
  944.             os.close(errpipe_read)
  945.             if data != '':
  946.                 os.waitpid(self.pid, 0)
  947.                 child_exception = pickle.loads(data)
  948.                 raise child_exception
  949.             
  950.  
  951.         
  952.         def _handle_exitstatus(self, sts):
  953.             if os.WIFSIGNALED(sts):
  954.                 self.returncode = -os.WTERMSIG(sts)
  955.             elif os.WIFEXITED(sts):
  956.                 self.returncode = os.WEXITSTATUS(sts)
  957.             else:
  958.                 raise RuntimeError('Unknown child exit status!')
  959.  
  960.         
  961.         def poll(self, _deadstate = None):
  962.             '''Check if child process has terminated.  Returns returncode
  963.             attribute.'''
  964.             if self.returncode is None:
  965.                 
  966.                 try:
  967.                     (pid, sts) = os.waitpid(self.pid, os.WNOHANG)
  968.                     if pid == self.pid:
  969.                         self._handle_exitstatus(sts)
  970.                 except os.error:
  971.                     if _deadstate is not None:
  972.                         self.returncode = _deadstate
  973.                     
  974.                 except:
  975.                     _deadstate is not None
  976.                 
  977.  
  978.             None<EXCEPTION MATCH>os.error
  979.             return self.returncode
  980.  
  981.         
  982.         def wait(self):
  983.             '''Wait for child process to terminate.  Returns returncode
  984.             attribute.'''
  985.             if self.returncode is None:
  986.                 (pid, sts) = os.waitpid(self.pid, 0)
  987.                 self._handle_exitstatus(sts)
  988.             
  989.             return self.returncode
  990.  
  991.         
  992.         def _communicate(self, input):
  993.             read_set = []
  994.             write_set = []
  995.             stdout = None
  996.             stderr = None
  997.             if self.stdin:
  998.                 self.stdin.flush()
  999.                 if input:
  1000.                     write_set.append(self.stdin)
  1001.                 else:
  1002.                     self.stdin.close()
  1003.             
  1004.             if self.stdout:
  1005.                 read_set.append(self.stdout)
  1006.                 stdout = []
  1007.             
  1008.             if self.stderr:
  1009.                 read_set.append(self.stderr)
  1010.                 stderr = []
  1011.             
  1012.             while read_set or write_set:
  1013.                 (rlist, wlist, xlist) = select.select(read_set, write_set, [])
  1014.                 if self.stdin in wlist:
  1015.                     bytes_written = os.write(self.stdin.fileno(), input[:512])
  1016.                     input = input[bytes_written:]
  1017.                     if not input:
  1018.                         self.stdin.close()
  1019.                         write_set.remove(self.stdin)
  1020.                     
  1021.                 
  1022.                 if self.stdout in rlist:
  1023.                     data = os.read(self.stdout.fileno(), 1024)
  1024.                     if data == '':
  1025.                         self.stdout.close()
  1026.                         read_set.remove(self.stdout)
  1027.                     
  1028.                     stdout.append(data)
  1029.                 
  1030.                 if self.stderr in rlist:
  1031.                     data = os.read(self.stderr.fileno(), 1024)
  1032.                     if data == '':
  1033.                         self.stderr.close()
  1034.                         read_set.remove(self.stderr)
  1035.                     
  1036.                     stderr.append(data)
  1037.                     continue
  1038.             if stdout is not None:
  1039.                 stdout = ''.join(stdout)
  1040.             
  1041.             if stderr is not None:
  1042.                 stderr = ''.join(stderr)
  1043.             
  1044.             if self.universal_newlines and hasattr(file, 'newlines'):
  1045.                 if stdout:
  1046.                     stdout = self._translate_newlines(stdout)
  1047.                 
  1048.                 if stderr:
  1049.                     stderr = self._translate_newlines(stderr)
  1050.                 
  1051.             
  1052.             self.wait()
  1053.             return (stdout, stderr)
  1054.  
  1055.  
  1056.  
  1057. def _demo_posix():
  1058.     plist = Popen([
  1059.         'ps'], stdout = PIPE).communicate()[0]
  1060.     print 'Process list:'
  1061.     print plist
  1062.     if os.getuid() == 0:
  1063.         p = Popen([
  1064.             'id'], preexec_fn = (lambda : os.setuid(100)))
  1065.         p.wait()
  1066.     
  1067.     print "Looking for 'hda'..."
  1068.     p1 = Popen([
  1069.         'dmesg'], stdout = PIPE)
  1070.     p2 = Popen([
  1071.         'grep',
  1072.         'hda'], stdin = p1.stdout, stdout = PIPE)
  1073.     print repr(p2.communicate()[0])
  1074.     print 
  1075.     print 'Trying a weird file...'
  1076.     
  1077.     try:
  1078.         print Popen([
  1079.             '/this/path/does/not/exist']).communicate()
  1080.     except OSError:
  1081.         e = None
  1082.         if e.errno == errno.ENOENT:
  1083.             print "The file didn't exist.  I thought so..."
  1084.             print 'Child traceback:'
  1085.             print e.child_traceback
  1086.         else:
  1087.             print 'Error', e.errno
  1088.     except:
  1089.         e.errno == errno.ENOENT
  1090.  
  1091.     print >>sys.stderr, 'Gosh.  No error.'
  1092.  
  1093.  
  1094. def _demo_windows():
  1095.     print "Looking for 'PROMPT' in set output..."
  1096.     p1 = Popen('set', stdout = PIPE, shell = True)
  1097.     p2 = Popen('find "PROMPT"', stdin = p1.stdout, stdout = PIPE)
  1098.     print repr(p2.communicate()[0])
  1099.     print 'Executing calc...'
  1100.     p = Popen('calc')
  1101.     p.wait()
  1102.  
  1103. if __name__ == '__main__':
  1104.     if mswindows:
  1105.         _demo_windows()
  1106.     else:
  1107.         _demo_posix()
  1108.  
  1109.